package com.guodi.map.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapGeneralTemplate;
import com.guodi.map.service.IMapGeneralTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
* @描述: 通用配图表 前端控制器
* @作者: 陈宏成
* @日期: 2021-11-12
*/
@Validated
@RestController
@RequestMapping("/MapGeneralTemplate")
@Api(value = "API - MapGeneralTemplateController", tags = "通用配图表")
public class MapGeneralTemplateController extends BaseController {

    @Resource
    private IMapGeneralTemplateService iMapGeneralTemplateService;


    /**
    * @描述：新增 通用配图表 记录
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    @PostMapping("/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "thumbnailFile", value = "缩略图文件", required = true)
    })
    @ApiOperation(value = "新增")
    @Transactional(rollbackFor = Exception.class)
    public R save(@Validated MapGeneralTemplate mapGeneralTemplate, MultipartFile thumbnailFile) throws IOException {
        // 新增前的验证数据，填充数据
        this.prepareBeforeSave(mapGeneralTemplate, thumbnailFile);
        // 上传缩略图
        String fileId = null;
        if(thumbnailFile != null) {
            fileId = MinioUtil.uploadFile(thumbnailFile.getInputStream(), "map_general_template", thumbnailFile.getOriginalFilename());
        } else {
//            fileId = MinioUtil.uploadFile(mapGeneralTemplate.getThumbnailText(), "map_general_template", thumbnailFile.getOriginalFilename());
        }
        mapGeneralTemplate.setThumbnailPath(fileId);
        // 新增
        boolean save = this.iMapGeneralTemplateService.save(mapGeneralTemplate);
        if (save){
            MapGeneralTemplate entity = this.iMapGeneralTemplateService.getById(mapGeneralTemplate.getId());
            return R.data(entity);
        }else{
            MinioUtil.removeFile(fileId);
            throw new RuntimeException("新增失败");
        }
    }

    /**
    * @描述：修改 通用配图表 记录
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    @Transactional(rollbackFor = Exception.class)
    public R<MapGeneralTemplate> update(@Validated MapGeneralTemplate mapGeneralTemplate, MultipartFile thumbnailFile) throws IOException {
        // 修改前的验证数据，填充数据
        this.prepareBeforeUpdate(mapGeneralTemplate, thumbnailFile);
        MapGeneralTemplate oldEntity = this.iMapGeneralTemplateService.getById(mapGeneralTemplate.getId());
        // 上传缩略图
        String oldFileId = null;
        String fileId = null;
        if (thumbnailFile != null){
            fileId = MinioUtil.uploadFile(thumbnailFile.getInputStream(), "map_general_template", thumbnailFile.getOriginalFilename());
            oldFileId = oldEntity.getThumbnailPath();
            mapGeneralTemplate.setThumbnailPath(fileId);
            mapGeneralTemplate.setThumbnailText("");
        }
        if(StringUtils.isNotBlank(mapGeneralTemplate.getThumbnailText())) {
            oldFileId = oldEntity.getThumbnailPath();
            mapGeneralTemplate.setThumbnailPath("");
        }
        // 修改
        boolean update = this.iMapGeneralTemplateService.updateById(mapGeneralTemplate);
        if (update){
            if (StringUtils.isNotBlank(oldFileId)){
                MinioUtil.removeFile(oldFileId);
            }
            return R.data(mapGeneralTemplate);
        }else{
            if (StringUtils.isNotBlank(oldFileId)){
                MinioUtil.removeFile(fileId);
            }
            throw new RuntimeException("修改失败");
        }
    }


    /**
    * @描述：删除 通用配图表 记录
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "主键id，如果多个，英文逗号隔开", required = true, dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R<List<MapGeneralTemplate>> delete(@Validated @NotBlank(message = "ids不能为空") String ids){
        List<String> idList = Arrays.asList(ids.trim().split(","));
        List<MapGeneralTemplate> mapGeneralTemplates = this.iMapGeneralTemplateService.listByIds(idList);
        boolean remove = this.iMapGeneralTemplateService.removeByIds(idList);
        if (remove){
            // 删除缩略图
            for(MapGeneralTemplate mapGeneralTemplate : mapGeneralTemplates) {
                MinioUtil.removeFile(mapGeneralTemplate.getThumbnailPath());
            }
            return R.data(mapGeneralTemplates);
        }else{
            throw new RuntimeException("删除失败");
        }
    }


    /**
    * @描述：获取 通用配图表 列表
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    @PostMapping("/page")
    @ApiOperation(value = "获取列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "size", value = "页面大小，默认10", dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "current", value = "当前页码，默认1",  dataType = "int", paramType = "query"),
    })
    public R<Page<MapGeneralTemplate>> page(@ApiIgnore Page page){
        LambdaQueryWrapper<MapGeneralTemplate> wrapper = new QueryWrapper<MapGeneralTemplate>().lambda();
        wrapper.orderByDesc(MapGeneralTemplate::getCreateTime);
        Page page1 = this.iMapGeneralTemplateService.page(page, wrapper);
        return R.data(page1);
    }



    /**
    * @描述：获取 通用配图表 详情
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    @PostMapping("/detail")
    @ApiOperation(value = "获取详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "string", paramType = "query")
    })
    public R<MapGeneralTemplate> detail(@Validated @NotBlank(message = "id不能为空") String id){
        MapGeneralTemplate mapGeneralTemplate = this.iMapGeneralTemplateService.getById(id);
        return R.data(mapGeneralTemplate);
    }



    /**
    * @描述：修改前的准备，包括验证数据和填充数据
    * @入参：MapGeneralTemplate
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    private void prepareBeforeUpdate(MapGeneralTemplate mapGeneralTemplate, MultipartFile thumbnailFile){
        if (thumbnailFile == null && StringUtils.isBlank(mapGeneralTemplate.getThumbnailText())){
            throw new RuntimeException("缩略图必须上传");
        }
        if (thumbnailFile != null && StringUtils.isNotBlank(mapGeneralTemplate.getThumbnailText())){
            throw new RuntimeException("缩略图只能上传一种");
        }
        if (StringUtils.isBlank(mapGeneralTemplate.getId())){
            throw new RuntimeException("请选择一条记录");
        }
        // 检验是否重名
        boolean b = this.iMapGeneralTemplateService.checkNameExist(mapGeneralTemplate.getName(), mapGeneralTemplate.getId());
        if (b == true){
            throw new RuntimeException("名称已存在");
        }
        MapGeneralTemplate byId = this.iMapGeneralTemplateService.getById(mapGeneralTemplate.getId());
        if (byId == null){
            throw new RuntimeException("记录不存在");
        }
        mapGeneralTemplate.setThumbnailPath(byId.getThumbnailPath());
        mapGeneralTemplate.setModifier(AuthUtil.getUserId().toString());
        mapGeneralTemplate.setModifyTime(new Date());
    }

    /**
    * @描述：新增前的准备，包括验证数据和填充数据
    * @入参：MapGeneralTemplate
    * @作者: 陈宏成
    * @日期: 2021-11-12
    */
    private void prepareBeforeSave(MapGeneralTemplate mapGeneralTemplate, MultipartFile thumbnailFile){
        if (thumbnailFile == null && StringUtils.isBlank(mapGeneralTemplate.getThumbnailText())){
            throw new RuntimeException("缩略图必须上传");
        }
        if (thumbnailFile != null && StringUtils.isNotBlank(mapGeneralTemplate.getThumbnailText())){
            throw new RuntimeException("缩略图只能上传一种");
        }
        // 检验是否重名
        boolean b = this.iMapGeneralTemplateService.checkNameExist(mapGeneralTemplate.getName(), null);
        if (b == true){
            throw new RuntimeException("名称已存在");
        }
        mapGeneralTemplate.setId(UuidUtil.get32UUID());
        mapGeneralTemplate.setCreator(AuthUtil.getUserId().toString());
        mapGeneralTemplate.setCreateTime(new Date());
    }
    
}
